package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.exception.SrbException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.listener.DictVoListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.entity.vo.DictVO;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2023-03-25
 */
//@EnableAsync //开启异步多线程
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    DictMapper dictMapper;

    @Override
    public void importDicts(MultipartFile file) {
        //判断文件类型
        if (!(file.getOriginalFilename().endsWith(".xls") || file.getOriginalFilename().endsWith(".xlsx"))){
            throw new SrbException(-108, "请上传excel文件！");
        }
        //判断文件大小
        if (file.getSize()==0){
            throw new SrbException(-107, "上传文件大小为0！");
        }
        //进行导入文件
        try {
            EasyExcel.read(file.getInputStream())
                    .sheet()
                    .head(DictVO.class)
                    .registerReadListener(new DictVoListener(this))
                    .doRead();
        } catch (IOException e) {
            throw new SrbException(ResponseEnum.IMPORT_DATA_ERROR);
        }
    }

    @Cacheable(value = "srb:dicts", key = "#pid")
    @Override
    public List<Dict> list(String pid) {
        /*//1.先查缓存，有就直接返回
        List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:dicts:" + pid);
        if (!CollectionUtils.isEmpty(dictList)){
            return dictList;
        }*/
        //2.缓存没有就查
        //根据pid查询父节点
        List<Dict> dictList = this.list(Wrappers.lambdaQuery(Dict.class)
                .eq(Dict::getParentId, pid));
        if (CollectionUtils.isEmpty(dictList)){
            return null;
        }
        dictList.forEach(dict -> {
            Boolean flag = hasChildren(dict.getId());
            dict.setHasChildren(flag);
        });
        /*//3.将查到的数据放入缓存
        redisTemplate.opsForValue().set("srb:dicts:" + pid, dictList);*/
        return dictList;
    }
    @Async
    public Boolean hasChildren(String id){
        return this.count(Wrappers.lambdaQuery(Dict.class).eq(Dict::getParentId, id))>0;
    }

    @Override
    public String getDictNameByCodeAndValue(String code, Integer value) {
        return dictMapper.getDictNameByCodeAndValue(code, value);
    }
}